package com.qiaofang.applet.service.other.service.impl;

import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.common.util.CaptchaUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.service.other.service.QiNiuService;
import com.qiaofang.applet.service.other.service.dto.QiniuUploadTokenQueryCriteria;
import com.qiaofang.core.gatewayclient.GatewayTemplate;
import com.qiniu.storage.model.DefaultPutRet;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * 七牛
 * @author
 * @date 2020-09-22
 */
@Slf4j
@Service
public class QiNiuServiceImpl implements QiNiuService {

    @Resource
    private GatewayTemplate gatewayTemplate;

    @Value("${qiniu.updateTokenUrl}")
    private String updateTokenUrl;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.viewUrl}")
    private String viewUrl;

    @Override
    public String getUploadToken() {
        try {
            QiniuUploadTokenQueryCriteria criteria = new QiniuUploadTokenQueryCriteria();
            criteria.setBucket(bucket);
            JSONObject result = gatewayTemplate.postForObject(updateTokenUrl, criteria, JSONObject.class);
            log.info("getUploadToken result is {}" ,result);
            return StringUtils.defaultString(result.getString("data"));
        } catch (Exception e) {
            log.error("getUploadToken error:",e);
            return "";
        }
    }

    @Override
    public String getUploadByByte(byte[] bytes) {
        try {
            //获取七牛token
            String upToken = getUploadToken();
            String fileNmae = UUID.randomUUID().toString().replace("-", "") + ".png";
            UploadManager uploadManager = new UploadManager(new Configuration(Region.region0()));
            Response response = uploadManager.put(bytes, fileNmae, upToken);
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return viewUrl + putRet.key;
        } catch (QiniuException e) {
            log.error("getUploadByByte error:", e);
        }
        return null;
    }
}
